package com.huangsm.book.designmodel.parallel.pcmodel;


import java.text.MessageFormat;
import java.util.Random;
import java.util.concurrent.BlockingQueue;

/**
 * 服务消费者
 * @author huang
 * @date 2019/2/19
 */
public class Consumer implements Runnable {
    /**
     * 缓冲区
     */
    private BlockingQueue<PCData>queue;
    private static final int SLEEPTIME=1000;

    public Consumer(BlockingQueue<PCData> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        System.out.println("start Consumer id="+Thread.currentThread().getId());
        //随机等待时间
        Random r=new Random();
        while (true){
            //提取任务
            try {
                PCData pcdata=queue.take();
                if (null!=pcdata){
                    //计算评分
                    int re= pcdata.getIntData()*pcdata.getIntData();
                    System.out.println(MessageFormat.format("{0}*{1}={2}",pcdata.getIntData(),pcdata.getIntData(),re));
                    Thread.sleep(r.nextInt(SLEEPTIME));
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                Thread.currentThread().interrupt();
            }
        }
    }
}
